import { login, getUserInfo, getUserDetailsByID } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const actions = {
  // 获取登录信息
  async login(store, data) {
    const res = await login(data)
    store.commit('setToken', res)
  },
  // 获取用户头像、id等信息
  async getUserInfo(store) {
    const res = await getUserInfo()

    const userInfo = await getUserDetailsByID(res.userId)

    store.commit('setUserInfo', { ...res, ...userInfo })
  },
  // 登出
  logOut(store) {
    resetRouter()
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }

}
const mutations = {
  setToken(state, data) {
    setToken(data)
    // 本地永久存储
    // localStorage.setItem('token', data)
    state.token = data
  },
  // 获取用户头像、id等信息
  setUserInfo(state, data) {
    state.userInfo = { ...data }
  },
  // 删除token
  removeToken(state) {
    // 移除cookie
    removeToken()
    // token等于空
    state.token = ''
  },
  // 删除用户数据
  removeUserInfo(state) {
    // 登出移除用户数据
    state.userInfo = {}
  }
}
const state = {
  // token: localStorage.getItem('token') || ''
  token: getToken() || '',
  userInfo: {} // 用户头像数据等
}
export default {
  namespaced: true,
  mutations,
  actions,
  state
}
